<template>
    <!-- 导入表 -->
    <el-dialog title="导入表" v-model="visible" width="900px" top="5vh" append-to-body>
        <vxe-grid ref="xGrid" v-if="visible" v-bind="gridOptions" @checkbox-change="handleSelectionChange"> </vxe-grid>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="handleImportTable">确 定</el-button>
                <el-button @click="visible = false">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
    import { ref, getCurrentInstance, reactive } from "vue";
    import { listDbTable, importTable } from "@/api/system/roleTable/table";
    import { VxeGridInstance, VxeGridProps, GridMethods, TableMethods, TableEditMethods, TableValidatorMethods } from "../../../../../types/index";
    import { gridComponentMethodKeys } from "@/components/ElementRender/src/methods";
    import XEUtils from "xe-utils";
    const visible = ref(false);
    const tables = ref([]);
    const { proxy } = getCurrentInstance() as any;
    const emit = defineEmits(["ok"]);
    const xGrid = ref({} as VxeGridInstance);
    const menuId = ref();
    const gridOptions = reactive<VxeGridProps>({
        border: true,
        resizable: true,
        showHeaderOverflow: true,
        showOverflow: true,
        highlightHoverRow: true,
        keepSource: true,
        id: "14",
        height: "600",
        rowId: "tableId",
        sortConfig: {
            trigger: "cell",
            remote: true,
        },
        filterConfig: {
            remote: true,
        },
        pagerConfig: {
            pageSize: 10,
            pageSizes: [5, 10, 15, 20, 50, 100, 200, 500, 1000],
            perfect: true,
        },
        formConfig: {
            titleWidth: 80,
            titleAlign: "right",
            items: [
                {
                    field: "tableName",
                    title: "表名称",
                    span: 9,
                    itemRender: { name: "$input", props: { placeholder: "请输入表名称" } },
                },
                {
                    field: "tableComment",
                    title: "表描述",
                    span: 9,
                    itemRender: { name: "$input", props: { placeholder: "请输入表描述" } },
                },
                {
                    itemRender: {
                        name: "$buttons",
                        children: [
                            {
                                props: {
                                    type: "submit",
                                    content: "查询",
                                    status: "primary",
                                },
                            },
                            {
                                props: {
                                    type: "reset",
                                    content: "重置",
                                },
                            },
                        ],
                    },
                },
            ],
        },
        toolbarConfig: {
            refresh: true,
            zoom: true,
            custom: true,
        },
        proxyConfig: {
            paramsChangeLoad: false, //额外的请求参数改变时是否重新请求数据
            seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
            sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
            filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
            form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
            // 对应响应结果 { result: [], page: { total: 100 } }
            props: {
                result: "rows", // 配置响应结果列表字段
                total: "total", // 配置响应结果总页数字段
            },
            ajax: {
                // 接收 Promise
                query: ({ page, sorts, filters, form, params }: any) => {
                    const queryParams: any = Object.assign({}, form);
                    // 处理排序条件
                    const orderByColumn = <Array<String>>[];
                    const isAsc = <Array<Boolean>>[];
                    sorts.forEach((m: any) => {
                        orderByColumn.push(m.field);
                        isAsc.push(m.order);
                    });
                    queryParams.orderByColumn = orderByColumn.join(",");
                    queryParams.isAsc = isAsc.join(",");
                    // 处理筛选条件
                    filters.forEach(({ property, values }: any) => {
                        queryParams[property] = values.join(",");
                    });
                    return listDbTable({
                        page: {
                            current: page.currentPage,
                            size: page.pageSize,
                        },
                        ...queryParams,
                        ...params,
                        menuId: menuId.value,
                    }).then((response: any) => {
                        return response;
                    });
                },
            },
        },
        checkboxConfig: {
            trigger: "row",
        },
        columns: [
            { type: "checkbox", width: 50 },
            {
                field: "tableName",
                title: "表名称",
                sortable: true,
            },
            {
                field: "tableComment",
                title: "表描述",
                sortable: true,
            },
            {
                field: "createTime",
                title: "创建时间",
                sortable: true,
                formatter({ cellValue }: any) {
                    return XEUtils.toDateString(cellValue, "yyyy-MM-dd HH:ss:mm");
                },
            },
            {
                field: "updateTime",
                title: "更新时间",
                sortable: true,
                formatter({ cellValue }: any) {
                    return XEUtils.toDateString(cellValue, "yyyy-MM-dd HH:ss:mm");
                },
            },
        ],
    });

    /** 查询参数列表 */
    function show(id: any) {
        menuId.value = id;
        visible.value = true;
    }
    /** 单击选择行 */
    function clickRow(row: any) {
        proxy.$refs.table.toggleRowSelection(row);
    }
    /** 多选框选中数据 */
    function handleSelectionChange(selection: any) {
        tables.value = selection.records.map((item: any) => item.tableName);
    }

    /** 搜索按钮操作 */
    function handleQuery() {
        xGrid.value.commitProxy("reload");
    }
    /** 重置按钮操作 */
    function resetQuery() {
        proxy.resetForm("queryRef");
        handleQuery();
    }
    /** 导入按钮操作 */
    function handleImportTable() {
        const tableNames = tables.value.join(",");
        if (tableNames == "") {
            proxy.$modal.msgError("请选择要导入的表");
            return;
        }
        importTable({ tables: tableNames, menuId: menuId.value }).then((res: any) => {
            proxy.$modal.msgSuccess(res.msg);
            if (res.code === 200) {
                visible.value = false;
                emit("ok");
            }
        });
    }
    const extendTableMethods = (methodKeys: any) => {
        const funcs: any = {};
        methodKeys.forEach((name: any) => {
            funcs[name] = (...args: any[]) => {
                const $vxegrid: any = xGrid.value;
                if ($vxegrid && $vxegrid[name]) {
                    return $vxegrid[name](...args);
                }
            };
        });
        return funcs;
    };

    const gridExtendTableMethods = extendTableMethods(gridComponentMethodKeys) as GridMethods & TableMethods & TableEditMethods & TableValidatorMethods;

    defineExpose({
        show,
        ...gridExtendTableMethods,
    });
</script>
